<?php
// 数据库连接类 - 单例模式实现
namespace core\db;

use PDO;
use PDOException;
use Exception;
use core\App;

class Database {
    // 单例实例
    private static $instance = null;
    // 数据库连接资源
    private $connection;

    // 私有构造函数，防止外部实例化
    private function __construct() {
        // 获取数据库配置
        $config = App::getConfig('database');

        try {
            // 提取配置参数
            $host = $config['host'] ?? 'localhost';
            $database = $config['database'] ?? '';
            $username = $config['username'] ?? '';
            $password = $config['password'] ?? '';
            $port = $config['port'] ?? 3306;
            $charset = $config['charset'] ?? 'utf8mb4';

            // 构建DSN
            $dsn = "mysql:host={$host};dbname={$database};port={$port};charset={$charset}";

            // 创建PDO连接
            $this->connection = new PDO(
                $dsn,
                $username,
                $password,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false
                ]
            );
        } catch (PDOException $e) {
            throw new Exception("数据库连接失败: " . $e->getMessage());
        }
    }

    // 防止克隆实例
    private function __clone() {}

    // 防止反序列化创建新实例
    public function __wakeup() {}

    // 静态方法获取单例实例
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    // 获取数据库连接
    public function getConnection() {
        return $this->connection;
    }

    // 执行查询
    public function query($sql, $params = []) {
        try {
            $stmt = $this->connection->prepare($sql);
            $stmt->execute($params);
            return $stmt;
        } catch (PDOException $e) {
            throw new Exception("查询执行失败: " . $e->getMessage());
        }
    }

    // 开始事务
    public function beginTransaction() {
        $this->connection->beginTransaction();
    }

    // 提交事务
    public function commit() {
        $this->connection->commit();
    }

    // 回滚事务
    public function rollBack() {
        $this->connection->rollBack();
    }
}